from app import db
from datetime import datetime
import uuid

class Certificate(db.Model):
    """证书模型"""
    __tablename__ = 'certificates'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    exam_record_id = db.Column(db.Integer, db.ForeignKey('exam_records.id'), nullable=False, comment='考试记录ID')
    certificate_no = db.Column(db.String(50), unique=True, nullable=False, comment='证书编号')
    title = db.Column(db.String(200), nullable=False, comment='证书标题')
    content = db.Column(db.Text, comment='证书内容')
    score = db.Column(db.Integer, nullable=False, comment='得分')
    issue_date = db.Column(db.Date, nullable=False, comment='颁发日期')
    certificate_url = db.Column(db.Text, comment='证书图片URL')
    is_valid = db.Column(db.Boolean, default=True, comment='是否有效')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __repr__(self):
        return f'<Certificate {self.certificate_no}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'exam_record_id': self.exam_record_id,
            'certificate_no': self.certificate_no,
            'title': self.title,
            'content': self.content,
            'score': self.score,
            'issue_date': self.issue_date.isoformat() if self.issue_date else None,
            'certificate_url': self.certificate_url,
            'is_valid': self.is_valid,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    @staticmethod
    def generate_certificate_no():
        """生成证书编号"""
        # 格式: HFB + 年月日 + 6位随机数
        date_str = datetime.now().strftime('%Y%m%d')
        random_str = str(uuid.uuid4().int)[:6]
        return f"HFB{date_str}{random_str}"
    
    @classmethod
    def create_certificate(cls, user_id, exam_record_id, score):
        """创建证书"""
        certificate = cls(
            user_id=user_id,
            exam_record_id=exam_record_id,
            certificate_no=cls.generate_certificate_no(),
            title="好爸爸证书",
            content=f"恭喜您通过月子护理知识考试，得分{score}分！",
            score=score,
            issue_date=datetime.now().date()
        )
        
        db.session.add(certificate)
        db.session.commit()
        
        return certificate 